package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.service.MinIOService;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-29
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private MinIOService minIOService;
    @Override
    public ResponseResult upload(MultipartFile file) {
        User user = UserThreadLocalUtil.get();
        if(ObjectUtils.isEmpty(user)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String url = minIOService.upload(file);
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getUserId());
        wmMaterial.setUrl(url);
        wmMaterial.setType(0);
        wmMaterial.setIsCollection(false);
        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult listByPage(WmMaterialDto wmMaterialDto) {
        Page<WmMaterial> page = new Page<>(wmMaterialDto.getPage(),wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        if (wmMaterialDto.getIsCollection()!=null) {
            queryWrapper.eq(WmMaterial::getIsCollection,wmMaterialDto.getIsCollection());
        }
        this.page(page,queryWrapper);
        return new PageResponseResult(wmMaterialDto.getPage(),wmMaterialDto.getSize(),page.getTotal(),page.getRecords());
    }
}
